package com.git.smp.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.git.smp.entity.SmpUser;

public class JWTUtil {

    // 过期时间2分钟
    private static final long EXPIRE_TIME = 24*60*60*1000;

    /**
     * 校验token是否正确
     * @param token 密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String secret,String version) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret+version);
            JWTVerifier verifier = JWT.require(algorithm).build();
            @SuppressWarnings("unused")
			DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }
    


    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userName").asString();
           
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    

    /**
     * 生成签名,5min后过期
     * @param userName 用户名
     * @param secret 用户的密码
     * @return 加密的token
     */
    public static String sign(SmpUser smpUser,long expireTime,String secret,String version) {
        try {
            Date date = new Date(System.currentTimeMillis()+expireTime);
            Algorithm algorithm = Algorithm.HMAC256(secret+version);
            // 附带username信息
            return JWT.create()
            		.withClaim("userName", smpUser.getUserName())
                    .withClaim("userChineseName", smpUser.getUserChineseName())
                    .withClaim("passWord", smpUser.getUserPasswd())
                    .withClaim("version", version)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }
}
